package common;

import java.util.Objects;

import static common.Constants.*;

/**
 * @author LinLe
 * @create 2020-12-22 7:52
 */
//对与发送消息的处理
public class ChatMessage {
    //发送方
    private String from;
    //接收方
    private String to;
    //发送的消息内容
    private String message;
    
    public ChatMessage() {
    }
    
    public ChatMessage(String from, String to, String message) {
        this.from = from;
        this.to = to;
        this.message = message.trim();
    }
    //对收到的信息进行解析，得到对发送方、接收方、消息内容，从而返回ChatMessage对象
    public static ChatMessage buildFrom(String message){
        ChatMessage cm = new ChatMessage();
        int fromEnd = message.indexOf(MESSAGE_SEP);
        cm.from = message.substring(0,fromEnd);
        int toEnd = message.indexOf(MESSAGE_SEP,fromEnd + 1);
        cm.to = message.substring(fromEnd+1,toEnd);
        cm.message = message.substring(toEnd + 1).trim();
        return cm;
    }
    //对发送方、接收方、消息内容进行同意格式处理(包装)
    public String toMessageString(){
        StringBuilder cm = new StringBuilder();
        cm.append(from).append(MESSAGE_SEP).append(to).append(MESSAGE_SEP).append(message).append(MESSAGE_SEP);
        return cm.toString();
    }
    
    @Override
    public String toString() {
        return "ChatMassage{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ChatMessage that = (ChatMessage) o;
        return from.equals(that.from) &&
                to.equals(that.to) &&
                message.equals(that.message);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(from, to, message);
    }
    
    public String getFrom() {
        return from;
    }
    
    public void setFrom(String from) {
        this.from = from;
    }
    
    public String getTo() {
        return to;
    }
    
    public void setTo(String to) {
        this.to = to;
    }
    
    public String getMessage() {
        return message;
    }
    
    public void setMessage(String message) {
        this.message = message;
    }
}
